﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.ServiceLocation;

namespace ThisIsFirstTest
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        // 从web.config中获取https的端口
        static string HttpsPort = System.Configuration.ConfigurationManager.AppSettings["HttpsPort"];

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            //Init Unity Container:
            InitUnityContainer();
        }

        //protected void Application_BeginRequest(Object sender, EventArgs e)
        //{
        //    if (!Request.IsSecureConnection)
        //    {
        //        string path = Request.Url.AbsoluteUri.Replace("http", "https");
        //        path = path.Replace(Request.Url.Port.ToString(), HttpsPort);
        //        Response.Redirect(path);
        //    }
        //}

        private void InitUnityContainer()
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = Server.MapPath("~/web.config");
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            ConfigurationSection section = config.GetSection(UnityConfigurationSection.SectionName);
            IUnityContainer container = new UnityContainer();
            container.LoadConfiguration((UnityConfigurationSection)section);
            ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
        }
    }
}